package sg.edu.nus.comp.icreate.ivletalk.forum;

import java.util.List;

import sg.edu.nus.comp.icreate.ivletalk.R;
import sg.edu.nus.comp.icreate.ivletalk.module.ElementType;
import sg.edu.nus.comp.icreate.ivletalk.module.MainActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;

public class ForumActivity extends ForumBaseActivity {
	public static final String EXTRA_NAME_HEADING_POSITION = "sg.edu.nus.comp.icreate.ivletalk.forum.headingPosition";
	public static final String EXTRA_NAME_THREAD_POSITION = "sg.edu.nus.comp.icreate.ivletalk.forum.threadPosition";
	private ExpandableListView threadList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		modulePosition = getIntent().getIntExtra(MainActivity.EXTRA_NAME_MODULE_POSITION, 0);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_forum);
		threadList = (ExpandableListView) findViewById(R.id.threadList);
		threadList.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
				((ForumActivity) parent.getContext()).goToThread(groupPosition, childPosition);
				return true;
			}

		});
		forum = (Forum) MainActivity.modules.get(modulePosition).getElements().get(ElementType.FORUM);
		try {
			threadList.setAdapter(new ForumExpandableListViewAdapter(forum.getHeadings(), this));
			getThreads();
			threadList.expandGroup(0);
		} catch (Exception e) {
			Log.e("err", "Error getting threads", e);
		}
	}

	public void goToThread(int groupPosition, int childPosition) {
		Intent intent = new Intent(this, ThreadActivity.class);
		intent.putExtra(MainActivity.EXTRA_NAME_MODULE_POSITION, modulePosition);
		intent.putExtra(EXTRA_NAME_HEADING_POSITION, groupPosition);
		intent.putExtra(EXTRA_NAME_THREAD_POSITION, childPosition);
		startActivity(intent);
	}

	protected void goToItem(int position) {
		// do nothing
	}

	@Override
	public boolean handleActionRefresh() {
		try {
			getThreads();
			((BaseAdapter) threadList.getAdapter()).notifyDataSetChanged();
		} catch (Exception e) {
			Log.e("error", "Error in handleActionRefresh", e);
		}
		return true;
	}

	@Override
	protected List<?> getDisplayedItemList() {
		// Do nothing
		return null;
	}

	@Override
	public Boolean goNewPost() {
		Intent intent = new Intent(getApplicationContext(), NewPostActivity.class);
		intent.putExtra(NewPostActivity.EXTRA_NAME_IS_REPLY, false);
		intent.putExtra(MainActivity.EXTRA_NAME_MODULE_POSITION, modulePosition);
		startActivityForResult(intent, NewPostActivity.REQUEST_CODE_NEW_POST);
		return true;

	}

}
